/**
 * Created by jiangxiaowei on 2017/4/25.
 */

import * as React from "react";
import { Relax } from "iflux2";
import { applyTpl } from "../../common/template-common";
import { Map } from "immutable";
import { getEnvXSite } from "x-site-util";
import { getSystemCodeZip } from "../../common/const-value";
import { message } from "antd";
import GaUtil from "common-util/ga-util";
import ExpireLock from "expire-lock";

declare let window: any;
const SystemCodeZip = getSystemCodeZip();

@Relax
export default class Template extends React.Component<any, any> {
  static defaultProps = {
    platform: "",
    templateInfo: Map(),
    activatedPageInfo: Map()
  };

  render() {
    let templateInfo = this.props.templateInfo.toJS();
    return (
      <div className="template">
        <img
          src={templateInfo.detailInfo && templateInfo.detailInfo.detailImage}
        />
        <div className="template-name">
          {templateInfo.templateName_cn}
        </div>
        <div>
          {templateInfo.detailInfo && templateInfo.detailInfo.desc}
        </div>
        <div className="template-img-mask" />
        <div
          className="template-modal-button-apply"
          onClick={this._applyTpl.bind(this)}
        >
          应用
        </div>
        <div
          className="template-modal-button-preview"
          onClick={this._previewTpl.bind(this)}
        >
          预览
        </div>
      </div>
    );
  }

  //应用模板
  @ExpireLock()
  _applyTpl() {
    let templateInfo = this.props.templateInfo.toJS();
    if (
      templateInfo.pageType !== "index" &&
      (!this.props.activatedPageInfo ||
        !this.props.activatedPageInfo.get(this.props.platform))
    ) {
      message.warn("请先发布您的首页！");
    } else {
      let url = applyTpl(templateInfo);
      window.open(url);
    }
    GaUtil.addTemplateEvent({
      eventAction: "应用模板",
      eventLabel: this.props.templateInfo.templateCode,
      platform: this.props.platform
    });
  }

  //预览模板
  @ExpireLock()
  _previewTpl() {
    let templateConfig = this.props.templateInfo.toJS();
    let url = templateConfig.detailInfo.previewHtml;
    let host = getEnvXSite();
    host = host.indexOf("http://") < 0 ? host.replace("//", "http://") : host;
    if (["weixin", "app"].indexOf(templateConfig.platForm) >= 0) {
      url =
        host +
        "/wxpreview?url=" +
        encodeURIComponent(url) +
        (["custom", "article", "liveShow"].indexOf(templateConfig.pageType) >= 0
          ? "&title=" +
            (templateConfig.templateName_cn || templateConfig.templateName)
          : "") +
        "&sc=" +
        SystemCodeZip;
    }
    window.open(url);
    GaUtil.addTemplateEvent({
      eventAction: "预览模板",
      eventLabel: this.props.templateInfo.templateCode,
      platform: this.props.platform
    });
  }
}
